package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.LeaveRequestDTO;
import com.cyzy.homework.service.LeaveRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 请假申请控制器
 */
@RestController
@RequestMapping("/api/leave-request")
@CrossOrigin(origins = "*")
public class LeaveRequestController {
    
    @Autowired
    private LeaveRequestService leaveRequestService;
    
    /**
     * 提交请假申请
     */
    @PostMapping
    public Result<LeaveRequestDTO> submitLeaveRequest(@RequestBody LeaveRequestDTO leaveRequestDTO) {
        try {
            LeaveRequestDTO result = leaveRequestService.submitLeaveRequest(leaveRequestDTO);
            return Result.success("请假申请提交成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID查询请假申请
     */
    @GetMapping("/{id}")
    public Result<LeaveRequestDTO> getLeaveRequestById(@PathVariable Long id) {
        try {
            LeaveRequestDTO result = leaveRequestService.getLeaveRequestById(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询请假申请列表
     */
    @GetMapping("/user/{userId}")
    public Result<Page<LeaveRequestDTO>> getLeaveRequestsByUserId(
            @PathVariable String userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "applyTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<LeaveRequestDTO> result = leaveRequestService.getLeaveRequestsByUserId(userId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID查询请假申请列表
     */
    @GetMapping("/class/{classId}")
    public Result<Page<LeaveRequestDTO>> getLeaveRequestsByClassId(
            @PathVariable String classId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "applyTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<LeaveRequestDTO> result = leaveRequestService.getLeaveRequestsByClassId(classId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID和状态查询请假申请列表
     */
    @GetMapping("/class/{classId}/status/{status}")
    public Result<Page<LeaveRequestDTO>> getLeaveRequestsByClassIdAndStatus(
            @PathVariable String classId,
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "applyTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<LeaveRequestDTO> result = leaveRequestService.getLeaveRequestsByClassIdAndStatus(classId, status, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据用户ID和状态查询请假申请列表
     */
    @GetMapping("/user/{userId}/status/{status}")
    public Result<Page<LeaveRequestDTO>> getLeaveRequestsByUserIdAndStatus(
            @PathVariable String userId,
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "applyTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<LeaveRequestDTO> result = leaveRequestService.getLeaveRequestsByUserIdAndStatus(userId, status, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新请假申请
     */
    @PutMapping("/{id}")
    public Result<LeaveRequestDTO> updateLeaveRequest(@PathVariable Long id, 
                                                    @RequestBody LeaveRequestDTO leaveRequestDTO) {
        try {
            LeaveRequestDTO result = leaveRequestService.updateLeaveRequest(id, leaveRequestDTO);
            return Result.success("请假申请更新成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除请假申请
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteLeaveRequest(@PathVariable Long id, 
                                           @RequestParam String userId) {
        try {
            leaveRequestService.deleteLeaveRequest(id, userId);
            return Result.success("请假申请删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户请假统计信息
     */
    @GetMapping("/user/{userId}/statistics")
    public Result<Object> getUserLeaveStatistics(@PathVariable String userId) {
        try {
            Object result = leaveRequestService.getUserLeaveStatistics(userId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取班级请假统计信息
     */
    @GetMapping("/class/{classId}/statistics")
    public Result<Object> getClassLeaveStatistics(@PathVariable String classId) {
        try {
            Object result = leaveRequestService.getClassLeaveStatistics(classId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 检查日期冲突
     */
    @GetMapping("/check-conflict")
    public Result<Boolean> checkDateConflict(
            @RequestParam String userId,
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam(required = false) Long excludeId) {
        try {
            boolean hasConflict = leaveRequestService.hasDateConflict(userId, startDate, endDate, excludeId);
            return Result.success(hasConflict);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
